const express = require("express");
const cors = require("cors");

// 导入jwt模块-token
const jwt = require("./app/config/jwt");
const expressJWT = require("express-jwt");

// 导入joi模块-参数校验
const Joi = require("joi");

// const morgan = require("morgan");
// const expressWs = require("express-ws");
// const schedule = require("node-schedule");
// const backupDatabase = require("./app/utils/backupDatabase");
require("dotenv").config();

// 创建服务器的实例对象
const app = express();

// 配置跨域
var corsOptions = {
  origin: "*",
};
app.use(cors(corsOptions));

app.use(express.json());

// 使用 .unless({path: [/^\/user\/register\//], 指定接口不需要进行Token身份认证
app.use(
  expressJWT({ secret: jwt.jwtSecretKey }).unless({
    path: [/^\/user\/register$/, /^\/user\/login$/],
  })
);

// 使用日志中间件
// app.use(morgan("dev"));

//  错误级别中间件
app.use(function (err, req, res, next) {
  //1 Joi 参数校验失败
  if (err instanceof Joi.ValidationError) {
    return res.json({
      status: 1,
      errorMsg: err.message,
    });
  }

  //2 捕获身份认证失败的错误
  if (err.name === "UnauthorizedError")
    return res.json({ status: 1, errorMsg: "身份认证失败！" });

  //n  未知错误
  res.json({
    status: 1,
    errorMsg: err.message,
  });
});

//  导入并使用路由模块
const userRouter = require("./app/router/userRouter");
const projectRouter = require("./app/router/projectRouter");
const needRouter = require("./app/router/needRouter");
const bugRouter = require("./app/router/bugRouter");
app.use("/user", userRouter);
app.use("/project", projectRouter);
app.use("/need", needRouter);
app.use("/bug", bugRouter);

// 设置监听端口
const PORT = 2443;
app.listen(PORT, () => {
  console.log(`服务器运行端口： ${PORT}.`);
});

const db = require("./app/models/index");
//表关联
require("./app/models/relaton");

// .sync()的作用:将定义的模型、表关联同步到数据库中去;
//数据库有相应表时无需调用
// db.sequelize.sync();
